﻿using System;
using System.IO;
using System.Collections.Generic;

namespace Draco.OWF.RT.Engine.Manager
{
    public class ActivityManager
    {
        IDictionary<String, ActivityPluginAgent> m_PluginAgents = new Dictionary<String, ActivityPluginAgent>();
        IDictionary<String, ActivityManifest> m_ActivityManifests = new Dictionary<String, ActivityManifest>();

        public void LoadActivities(String activityRepoURL)
        {
            if (String.IsNullOrWhiteSpace(activityRepoURL)) return;
            if (!Directory.Exists(activityRepoURL)) return;
            String[] paths = Directory.GetFiles(activityRepoURL);
            foreach (String path in paths)
            {
                String manifestPath = Path.Combine(path, "ActivityManifest.xml");
                if (File.Exists(manifestPath))
                {
                    ActivityPluginAgent aAgent = new ActivityPluginAgent(path);
                    m_PluginAgents.Add(aAgent.PluginName, aAgent);

                    List<ActivityManifest> manifests = aAgent.getActivityManifest();
                    foreach (ActivityManifest manifest in manifests)
                    {
                        m_ActivityManifests.Add(manifest.Name, manifest);
                    }
                }
            }
        }

        public Type GetActivityType(String activityType)
        {
            ActivityManifest manifest = m_ActivityManifests[activityType];
            if (manifest != null)
            {
                String pluginName = manifest.Manifest.PluginName;
                ActivityPluginAgent pluginAgent = m_PluginAgents[pluginName];
                return pluginAgent.GetActivityType(activityType);
            }
            return null;
        }

        public Object GetActivityInstance(String activityType)
        {
            Type type = GetActivityType(activityType);
            Object obj = Activator.CreateInstance(type);
            return obj;
        }
    }
}
